﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

using Tao.DevIl;

#region Copyright (c) 2006, 2007, 2008, 2009 Render Studio Foundation. All rights reserved.

/*
 Copyright (c) 2006, 2007, 2008, 2009 Render Studio Foundation. All rights reserved.
 This work is copyrighted in its entirety. Permission to use "Render Studio"
 material may be granted only after we receive a written request from you,
 and you receive written permission from us.

 While Render Studio Foundation provides the information herein to anyone,
 we retain copyright on all code, text, graphic images, and other content.
 This means that you may not distribute the code, the text or graphics to others without the
 express written permission of Render Studio Foundation; "mirror" this information on your server
 without our permission; or modify or reuse the code, text or graphics on our servers.
 You may print copies of the information for your own personal use; and, you may reference
 the Service from your own documents. Any commercial use of this material is prohibited without
 the written permission of Render Studio Foundation. In all copies of this information, you must
 retain this notice and any other copyright notices originally included with such information.

 This material may be protected by U.S. and International Copyright laws, and you are legally
 bound by the copyright notices on those systems.

 "Render Studio" logos and other official symbols or graphics may not be used in connection with any
 product or service that has not been expressly authorized in advance in writing or in any manner
 that is likely to cause confusion among the users of this or other Web sites or among the public.
 All other seals, graphics or trademarks of organizations not affiliated with Render Studio Foundation
 that appear on this site are the property of their respective owners.

 Render Studio Foundation reserve all other rights. 
*/

#endregion

#region Render Studio Source Code Licence

/*
This license governs use of the Render Studio software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Summary

The source code is made available to view for reference purposes or to contribute to the project only. Developers may not distribute or modify the code for commercial or non-commercial purposes without express Agreement of Render Studio Foundation.

2. Definitions

The terms "reproduce," "reproduction," and "distribution" have the same meaning here as under U.S. copyright law.
"Licensor" means the foundation "Render Studio Foundation".
"You" means the licensee of the software, who is not engaged in designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software.
"Your company" means the company you worked for when you downloaded the software.
"Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes of debugging and maintaining your products. For clarity, "reference use" does NOT include (a) the right to use the software for purposes of designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software, and (b) the right to distribute the software outside of your company.
"Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor under this license.

3. Grant of Rights

(A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free copyright license to reproduce the software for reference use.
(B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free patent license under licensed patents for reference use.
4. Limitations
(A) No Trademark License- This license does not grant you any rights to use the Licensor's name, logo, or trademarks.
(B) If you begin patent litigation against the Licensor over patents that you think may apply to the software (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically.
(C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */

#endregion

namespace RSEngine.Media
{

    /// <summary>
    /// This class manage all the imaging related features.
    /// </summary>
    static public class ImageCodec
    {

        #region Constructor

        static ImageCodec()
        {
            // Initialize DevIL
            Il.ilInit();
        }

        #endregion

        #region LoadGLImage

        /// <summary>
        /// Load a image and returns an ILImage that can be used
        /// directly as an OpenGl texture.
        /// </summary>
        static public ILImage LoadGLImage(string inputFile, bool useMipMaps)
        {
            ILImage image = new ILImage();

            if (Il.ilGetInteger(Il.IL_VERSION_NUM) < Il.IL_VERSION ||
                Il.ilGetInteger(Ilu.ILU_VERSION_NUM) < Ilu.ILU_VERSION ||
                Il.ilGetInteger(Ilut.ILUT_VERSION_NUM) < Ilut.ILUT_VERSION)
            {
                //Console.WriteLine("*** Your DevIL native libraries are older than what Tao.DevIl supports, get the latest DevIL native libraries. ***");
                //Console.WriteLine("Your DevIL native IL version: {0}.  Tao.DevIl's IL version: {1}.", Il.ilGetInteger(Il.IL_VERSION_NUM), Il.IL_VERSION);
                //Console.WriteLine("Your DevIL native ILU version: {0}.  Tao.DevIl's ILU version: {1}.", Il.ilGetInteger(Ilu.ILU_VERSION_NUM), Ilu.ILU_VERSION_NUM);
                //Console.WriteLine("Your DevIL native ILUT version: {0}.  Tao.DevIl's ILUT version: {1}.", Il.ilGetInteger(Ilut.ILUT_VERSION_NUM), Ilut.ILUT_VERSION_NUM);
                throw new NotSupportedException("Your DevIL native libraries are older than what Tao.DevIl supports.");
            }

            // Some nVidia cards have this "feature" where they will automatically convert all images
            // to 16-bit to save memory.
            // This is good and all, but it introduces dithering effects.
            // What this does is send a different value as the internalFormat parameter of glTexImage2D.
            // The new values are GL_RGB8 and GL_RGBA8 instead of GL_RGB and GL_RGBA, respectively. 
            //Ilut.ilutEnable(Ilut.ILUT_OPENGL_CONV);

            // Initialize DevIL
            Il.ilInit();

            // Generate the main image name to use
            Il.ilGenImages(1, out image.ILImageId);

            // Bind this image name
            Il.ilBindImage(image.ILImageId);

            // Loads the image into the imageId
            if (!Il.ilLoadImage(inputFile))
            {
                string message = string.Format("Could not open file, {0}, exiting.", inputFile);
                throw new NotSupportedException(message);
            }

            // Convert every colour component into
            // unsigned byte. If your image contains alpha channel you can replace IL_RGB with IL_RGBA 
            Il.ilConvertImage(Il.IL_RGB, Il.IL_UNSIGNED_BYTE); // IL_BGRA

            //// Done with the imageId, so let's delete it
            //Il.ilDeleteImages(1, ref imageId);

            // Before you call any ilut functions dealing with OpenGL and after you have initialized OpenGL
            Ilut.ilutRenderer(Ilut.ILUT_OPENGL);

            //image.Data = Il.ilGetData();
            image.Width = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
            image.Height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);
            //image.Depth = Il.ilGetInteger(Il.IL_IMAGE_DEPTH);
            //image.IL_IMAGE_BITS_PER_PIXEL = Il.ilGetInteger(Il.IL_IMAGE_BITS_PER_PIXEL);
            

            if (useMipMaps)
            {
                bool r = Ilut.ilutGLBuildMipmaps();
                image.GLImageId = Ilut.ilutGLBindMipmaps();
            }
            else
            {
                image.GLImageId = Ilut.ilutGLBindTexImage();
            }

            // Delete the image because now it is linked to Open Gl
            Il.ilBindImage(0);
            Il.ilDeleteImage(image.ILImageId);
            image.ILImageId = -1;

            return image;
        }

        #endregion

    }

    #region ILImage

    public struct ILImage
    {
        public int Width;
        public int Height;

        /// <summary>
        /// The Open Gl image/texture id.
        /// </summary>
        public int GLImageId;

        /// <summary>
        /// The IL imageId
        /// </summary>
        public int ILImageId;
    }

    #endregion

}
